package com.voxel.sense.infomsg.module.task.execution.file;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.example.com.common.app.BViewActivity;
import com.example.com.common.utils.SnackbarUtils;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.view.dialog.DialogCallBack;
import com.example.com.common.view.dialog.DialogImpl;
import com.example.com.common.view.recycler.RecyclerAdapter;
import com.tencent.mmkv.MMKV;
import com.voxel.sense.infomsg.App;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.MultiItemBean;
import com.voxel.sense.infomsg.interfaces.listener.AddItemPortionClickListener;
import com.voxel.sense.infomsg.utils.AppFileUtil;
import com.voxel.sense.infomsg.view.decoration.TaskFileItemDivider;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.share.SPEngine;
import droidninja.filepicker.FilePickerBuilder;
import droidninja.filepicker.FilePickerConst;
import droidninja.filepicker.utils.Orientation;

public class TaskFileOperationActivity extends BViewActivity<TaskFileOperationContract.Presenter>
  implements TaskFileOperationContract.View {
  private final int max_num = 13; //最多能够选择文件的数量
  public final static String[] docExtensions = {"txt", "xls", "xlsx", "doc", "docx", "dot", "dotx", "pdf"};
  @BindView(R.id.recycle_view)
  RecyclerView recycle_view;
  @BindView(R.id.titlebar)
  TextTitleBar titlebar;
  @BindView(R.id.et_advice)
  EditText mAdvice;
  TaskFileOperationAdapter mAdapter;
  private int mImageFilesCount;
  private int mDocCount;
  private int operaType;
  private static String taskDesc;
  private MMKV mmkv;

  public static void show(Context context, String taskNumb, int operaType) {
    Intent intent = new Intent(context, TaskFileOperationActivity.class);
    intent.putExtra(IntentConstants.TASK_NUMB, taskNumb);
    intent.putExtra(IntentConstants.TASK_OPERATYPE, operaType);
    context.startActivity(intent);
  }

  @Override
  protected int getContentLayoutId() {
    return R.layout.activity_task_operation;
  }

  @Override
  protected TaskFileOperationContract.Presenter initPresenter() {
    return new TaskFileOperationPresenter(this, this);
  }

  @Override
  protected void initData() {
    super.initData();
    titlebar.setTitleText("上传附件");
    mmkv = MMKV.defaultMMKV();
    operaType = getIntent().getIntExtra(IntentConstants.TASK_OPERATYPE, 0);
    mAdapter = new TaskFileOperationAdapter();
    GridLayoutManager manager = new GridLayoutManager(this, 3);
    manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
      @Override
      public int getSpanSize(int position) {
        int type = mAdapter.getItems().get(position).getType();
        if (type == TaskFileOperationContract.ADD_TYPE || type == TaskFileOperationContract.IMAGE_DESC_TYPE ||
          type == TaskFileOperationContract.DOC_DESC_TYPE) {
          return 3;
        }
        return 1;
      }
    });

    recycle_view.setAdapter(mAdapter);
    recycle_view.setLayoutManager(manager);
    recycle_view.addItemDecoration(new TaskFileItemDivider());
    String taskNumb = getIntent().getStringExtra(IntentConstants.TASK_NUMB);
    mPresenter.getFileList(taskNumb);

  }

  private void showPassBtn() {
    switch (operaType) {
      case 0:
        titlebar.setRightVisible(false);
        break;
      case 1:
        titlebar.setRightVisible(true);
        break;
      default:
        titlebar.setRightVisible(true);
        break;
    }
  }

  @Override
  protected void initEven() {
    super.initEven();
    mAdapter.setListener(new RecyclerAdapter.AdapterListenerImpl<MultiItemBean<String>>() {
      @Override
      public void onItemClick(RecyclerAdapter.ViewHolder holder, MultiItemBean<String> bean) {
        super.onItemClick(holder, bean);
        taskDesc = mAdvice.getText().toString().trim();
        mmkv.encode("OPERATION_CODE", taskDesc);
        int type = bean.getType();
        if (type == TaskFileOperationContract.ADD_TYPE) {

          pickClickEvent(bean);
        }
        else if (type == TaskFileOperationContract.LOCAL_IMAGE_TYPE || type == TaskFileOperationContract.NET_IMAGE_TYPE) {
          //点击图片
//                    lookImage(bean.get);
        }
        else if (type == TaskFileOperationContract.LOCAL_DOC_TYPE || type == TaskFileOperationContract.NET_DOC_TYPE) {
          mPresenter.LookDocs(bean);
        }
      }
    });

    mAdapter.setItemDeletedListener(new AddItemPortionClickListener<MultiItemBean<String>>() {
      @Override
      public void onItemChildViewClick(View childView, int position, MultiItemBean<String> bean) {
        mPresenter.removeFile(mAdapter.getItems(), bean);
        if (bean.getType() == TaskFileOperationContract.LOCAL_DOC_TYPE ||
          bean.getType() == TaskFileOperationContract.NET_DOC_TYPE) {
          //TODO: 删除数目不正确
          mDocCount--;
        }
        else if (bean.getType() == TaskFileOperationContract.LOCAL_IMAGE_TYPE ||
          bean.getType() == TaskFileOperationContract.NET_IMAGE_TYPE) {
          mImageFilesCount--;
        }
      }
    });

    titlebar.setRightTextAndLis("保存", new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        String taskNumb = getIntent().getStringExtra(IntentConstants.TASK_NUMB);
        String desc = mAdvice.getText().toString().trim();
        if (TextUtils.isEmpty(desc)) {
          ToastUtil.showToastShort(TaskFileOperationActivity.this, "问题反馈不能为空");
          return;
        }
        mPresenter.doUploadFile(taskNumb, mAdapter.getItems(), desc, null);
      }
    });
    showPassBtn();
  }

  @Override
  public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
    super.onSaveInstanceState(outState, outPersistentState);
    mAdvice.onSaveInstanceState();
  }

  private void pickClickEvent(MultiItemBean bean) {
    if ((mDocCount + mImageFilesCount) < max_num) {
      //点击最后一个，则是添加图片
      List<String> list = new ArrayList<>();
      list.add("添加图片");
      list.add("添加文档");
      DialogImpl.getInstance().showItemDialog(this, "", list, new DialogCallBack() {
        @Override
        public void onClick(int what) {
          if (what == 0) {
            onShowPickPhotoUI();
          }
          else {
            addDoc();
          }
        }
      });
    }
    else {
      //查看图片
//            CommonImagePagerActivity.showImages(PublishFileActivity.this, mImageAdapter.getDatasPath(), position);
      SnackbarUtils.with(recycle_view).setMessage("最多只能添加13个附件").showWarning();
    }
  }

  private void onShowPickPhotoUI() {
    List<MultiItemBean<String>> items = mAdapter.getItems();
    ArrayList<String> pathData = new ArrayList<>();
    int netImageCont = 0;
    for (MultiItemBean<String> bean : items) {
      if (TaskFileOperationContract.LOCAL_IMAGE_TYPE == bean.getType()) {
        pathData.add(bean.getData());
      }
      else if (TaskFileOperationContract.NET_IMAGE_TYPE == bean.getType()) {
        netImageCont++;
      }
    }
    int selectCount = max_num - mDocCount - netImageCont;
    FilePickerBuilder.getInstance().setMaxCount(selectCount)
      .setSelectedFiles(pathData)
      .setActivityTheme(R.style.FilePickerTheme)
      .enableImagePicker(true)
      .enableVideoPicker(false)//是否能视频图片
      .enableCameraSupport(false)//是否有照相item
      .showGifs(false)//是否显示gif图
      .showFolderView(false)//是否显示文件夹
      .enableSelectAll(true)//是否选中全部，这个选中只有没有选中数量的情况下才能使用
      .setCameraPlaceholder(R.mipmap.custom_camera)//相机图片
      .withOrientation(Orientation.UNSPECIFIED)
      .pickPhoto(this);//显示文件

  }

  @Override
  public void onRefreshFilesList(List list) {

    mAdapter.replace(list);
  }

  @Override
  public void onUploadSuccess() {

  }

  @Override
  public void onUploadFailure() {

  }

  @Override
  public void notifychange() {
    mAdapter.notifyDataSetChanged();
  }

  @Override
  public void onRecordImageCount(int imageCount, String content) {
    mImageFilesCount = imageCount;
    if (!TextUtils.isEmpty(content)) {
      mAdvice.setText(content + "");
      mmkv.encode("OPERATION_CODE", content);
    }
  }

  @Override
  public void onRecordDocCount(int docCount) {
    mDocCount = docCount;
  }

  /**
   * 拉起文档选择器 mentally
   */
  private void addDoc() {
    List<MultiItemBean<String>> items = mAdapter.getItems();
    ArrayList<String> list = new ArrayList<>();
    int netDocCount = 0;
    for (MultiItemBean<String> itemBean : items) {
      if (itemBean.getType() == TaskFileOperationContract.LOCAL_DOC_TYPE) {
        list.add(itemBean.getData());
      }
      else if (itemBean.getType() == TaskFileOperationContract.NET_DOC_TYPE) {
        netDocCount++;
      }
    }
    //扫描微信及qq下的文件夹
    AppFileUtil.MediaStoreScanTencent();
    int selectCount = max_num - mImageFilesCount - netDocCount;
    String[] docExtensions = {"doc", "docx"};
    String[] pdfExtensions = {".pdf"};
    String[] excelExtensions = {"xls", "xlsx"};
    String[] txtExtensions = {".txt"};
    String PDF = "PDF";
    String DOC = "DOC";
    String XLS = "XLS";
    String TXT = "TXT";
    FilePickerBuilder.getInstance().setMaxCount(selectCount)
      .setSelectedFiles(list)
      .setActivityTheme(R.style.FilePickerTheme)
      .addFileSupport(PDF, pdfExtensions)
      .addFileSupport(DOC, docExtensions)
      .addFileSupport(XLS, excelExtensions)
      .addFileSupport(TXT, txtExtensions)
      .enableDocSupport(false)
      .showFolderView(false)//是否显示文件夹
      .enableSelectAll(true)//是否选中全部，这个选中只有没有选中数量的情况下才能使用
      .withOrientation(Orientation.UNSPECIFIED)
      .pickFile(this);
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == Activity.RESULT_OK) {
      if (requestCode == FilePickerConst.REQUEST_CODE_PHOTO) {
        //选取图片结果
        ArrayList<String> photoResult = data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA);
        mPresenter.doAddImage(mAdapter.getItems(), photoResult);
      }
      else if (requestCode == IntentConstants.REQUEST_CODE_TAKE_PHOTO) {
        //得到拍照结果
      }
      else if (requestCode == FilePickerConst.REQUEST_CODE_DOC) {
        //文档回调
        getSelectDocuResult(data);
      }
    }

    String operation_code = mmkv.decodeString("OPERATION_CODE");
    mAdvice.setText(operation_code);
  }

  private void getSelectDocuResult(Intent data) {
    ArrayList<String> bean = data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_DOCS);
    mPresenter.doAddSelelctDocs(mAdapter.getItems(), bean);
  }

  @Override
  public void showSnackBarWarning(String str) {
    super.showSnackBarWarning(str);
    SnackbarUtils.with(recycle_view).setMessage(str).showWarning();
  }

}
